package com.sys.plat.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.sys.plat.bean.PageBean;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;

import com.sys.plat.web.core.ActionContext;

public class HttpUtil {

    public static HttpServletRequest getRequest() {
        return ActionContext.getRequest();
    }

    /**
     * =request.getParameter(name)
     *
     * @param name
     * @return
     */
    public static String getParameter(String name) {
        return ActionContext.getRequest().getParameter(name);
    }

    /**
     * =request.getParameterValues(name)
     *
     * @param name
     * @return
     */
    public static String[] getParameters(String name) {
        return ActionContext.getRequest().getParameterValues(name);
    }

    /**
     * =request.setAttribute(key,obj)
     *
     * @param key
     * @param obj
     */
    public static void reqSetAttr(String key, Object obj) {
        ActionContext.getRequest().setAttribute(key, obj);
    }

    /**
     * =request.removeAttribute(key)
     *
     * @param key
     */
    public static void reqRmvAttr(String key) {
        ActionContext.getRequest().removeAttribute(key);
    }

    /**
     * =request.removeAttribute(key)
     *
     * @param key
     */
    public static void reqGetAttr(String key) {
        ActionContext.getRequest().getAttribute(key);
    }

    /**
     * =session.setAttribute(key,obj)
     *
     * @param key
     * @param obj
     */
    public static void sessionSetAttr(String key, Object obj) {
        ActionContext.getRequest().getSession().setAttribute(key, obj);
    }

    /**
     * @param key
     * @return
     */
    public static Object sessionGetAttr(String key) {
        return ActionContext.getRequest().getSession().getAttribute(key);
    }

    /**
     * =session.removeAttribute(key)
     *
     * @param key
     */
    public static void sessionRmvAttr(String key) {
        ActionContext.getRequest().getSession().removeAttribute(key);
    }

    public static String saveParemeter(boolean bool, String... names) {

        // pageno,pagesize,f()
        String inputhidden = "<INPUT TYPE='HIDDEN' NAME='${name}' VALUE='${value}' >";
        List<String> keylist = new ArrayList<String>();
        Map map = ActionContext.getRequest().getParameterMap();
        if (names != null) {
            for (String key : names) {
                keylist.add(key);
            }
        }
        StringBuffer sb = new StringBuffer();
        for (String key : keylist) {
            Object obj = map.get(key);
            if (obj != null && obj instanceof String[]) {
                obj = ((String[]) obj)[0];
            }
            if (obj == null)
                obj = "";
            sb.append(inputhidden.replace("${name}", key).replace("${value}",
                    obj.toString()));
            if (bool) {
                reqSetAttr("sys_save_" + key, obj.toString());
            }
        }
        reqSetAttr("sys_saveparemeter", sb.toString());
        return sb.toString();
    }

    public static String saveParemeters(String name) {

        // pageno,pagesize,f()
        String inputhidden = "<INPUT TYPE='HIDDEN' NAME='${name}' VALUE='${value}' >";
        String[] parameterValues = ActionContext.getRequest()
                .getParameterValues(name);

        StringBuffer sb = new StringBuffer();
        if (parameterValues != null) {
            for (String key : parameterValues) {
                sb.append(inputhidden.replace("${name}", name).replace(
                        "${value}", key));
            }
        }
        return sb.toString();
    }

    /**
     * shiming 得到ip
     *
     * @return
     */
    public static String getIpAddr() {
        return ActionContext.getRequest().getRemoteAddr();
    }

    @SuppressWarnings("unchecked")
    public static String saveSearchParemeter(String... names) {

        // pageno,pagesize,f()
        String inputhidden = "<INPUT TYPE='HIDDEN' NAME='${name}' VALUE='${value}' >";
        List<String> keylist = new ArrayList<String>();
        Map map = ActionContext.getRequest().getParameterMap();
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            if (key.startsWith("f(") && key.endsWith(")")) {
                keylist.add(key);
            }
        }
        keylist.add("pageno");
        keylist.add("pagesize");
        keylist.add("order");
        keylist.add("property");

        if (names != null) {
            for (String key : names) {
                keylist.add(key);
            }
        }
        StringBuffer sb = new StringBuffer();
        for (String key : keylist) {
            Object obj = map.get(key);
            if (obj != null && obj instanceof String[]) {
                obj = ((String[]) obj)[0];
            }
            if (obj == null)
                obj = "";
            sb.append(inputhidden.replace("${name}", key).replace("${value}",
                    obj.toString()));
        }
        reqSetAttr("sys_searchparemeter", sb.toString());
        return sb.toString();
    }

    /**
     * Method getFilterParameter ... liudecai
     *
     * @param name of type String
     * @return String
     */
    public static String getFilterParameter(String name) {
        String inputText = getParameter(name);
        if (inputText == null)
            return "";
        if (inputText.trim().length() == 0)
            return "";
        inputText = StringUtils.replace(inputText, "\"", "&quot;");
        return inputText;
    }

    public static String getRealPath(String httpPath) {
        return ActionContext.getRequest().getSession().getServletContext()
                .getRealPath(httpPath);
    }

    public static void sendRedirect(String url) {
        try {
            ActionContext.getResponse().sendRedirect(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * lIst转化成Json形式，显示到页面
     *
     * @param pageBean
     */
    public static void ListToJSONByModel(PageBean pageBean) {
        ListToJSONByModel(pageBean.getRetList(), pageBean.getTotalrow());
    }

    public static void ListToJSONByModel(List list, int totalrow) {

        StringBuffer sb = new StringBuffer();

        sb.append("{totalProperty:").append(totalrow).append(",");
        sb.append("root:[");

        for (int i = 0; i < list.size(); i++) {
            try {
                Map map = BeanUtils.describe(list.get(i));
                sb.append("{");

                Object[] key = map.keySet().toArray();
                for (int j = 0; j < key.length; j++) {
                    sb.append("'").append(key[j]).append("':");

                    String value = BeanUtils.getProperty(list.get(i), String.valueOf(key[j]));
                    if (value == null || value.equals("null"))
                        value = "";

                    value = value.replaceAll("'", "\"");
                    sb.append("'").append(value).append("'");

                    if (j != key.length - 1) {
                        sb.append(",");
                    }
                }

                sb.append("}");
            } catch (IllegalAccessException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            } catch (InvocationTargetException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            } catch (NoSuchMethodException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
            if (i != list.size() - 1) {
                sb.append(",");
            }
        }

        sb.append("]}");

        String outStr = sb.toString();

        outStr = outStr.replaceAll("\r\n", "");
        outStr = outStr.replaceAll("\t", "");
        outStr = outStr.replaceAll("\n", "");

        //System.out.println(outStr);
        try {
            PrintWriter out = ActionContext.getResponse().getWriter();
            out.print(outStr);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public static void printOutToWeb(String outStr) {
        try {
            PrintWriter out = ActionContext.getResponse().getWriter();
            out.print(outStr);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }


    /**
     * 将查询条件初始化至页面
     * @param objs
     */
    public static void fiterToWeb(Object[][] objs) {

        Map map;

        StringBuffer sb = new StringBuffer();

        sb.append("{");
        for (Object[] obj : objs) {
            sb.append("'").append(obj[0]).append("':[");
            map = (Map) obj[1];
            StringBuffer sb2 = new StringBuffer();
            for (Object o : map.keySet()) {
                if (o.toString().indexOf("#") > -1) {//以#开头的，不加f(),不走默认查询模块
                    sb2.append("['").append(o.toString().substring(1)).append("','").append(map.get(o)).append("'],");
                }else{
                    sb2.append("['f(").append(o.toString()).append(")','").append(map.get(o)).append("'],");
                }

            }
            sb.append(sb2.substring(0, sb2.length() - 1) + "],");
        }


        reqSetAttr("page_fiter", sb.substring(0, sb.length() - 1)+"}");
    }
}


